﻿namespace WebApi.Commons.Helpers
{
    /// <summary>
    /// 上传文件帮助类
    /// </summary>
    public class UploadHelper
    {
        /// <summary>
        /// 上传前端文件
        /// </summary>
        /// <param name="files"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static List<string> UploadFiles(IFormFileCollection files, string filePath)
        {
            var result = new List<string>();
            if (!files.Any())
            {
                LoggerHelper.Warn(LogEnum.System, "未找到上传的文件");
            }

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            try
            {
                foreach (var file in files)
                {
                    string suffix = DateTime.Now.ToString("yyyyMMddHHmmss");
                    string filetype = Path.GetExtension(file.FileName);
                    string origin_filename = Path.GetFileNameWithoutExtension(file.FileName);
                    var filename = origin_filename + "_" + suffix + filetype;

                    using (FileStream filestream = File.Create(filePath + filename))
                    {
                        file.CopyTo(filestream);
                    }

                    result.Add(filename);
                    LoggerHelper.Info(LogEnum.System, "上传文件:" + filePath + filename + " saved");
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Error(LogEnum.System, "上传文件失败", ex);
            }
            return result;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileBytes"></param>
        /// <param name="filePath"></param>
        public static string UploadFile(byte[] fileBytes, string filePath)
        {
            try
            {
                var directoryPath = filePath.Substring(0, filePath.Contains('/') ? filePath.LastIndexOf('/') : filePath.LastIndexOf('\\'));
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                }
                using (var fstream = new FileStream(filePath, FileMode.Create))
                {
                    fstream.Write(fileBytes, 0, fileBytes.Length);
                    fstream.Close();
                }
                return filePath;
            }
            catch
            {
                return string.Empty;
            }
        }
    }
}
